package com.zhixue.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhixue.content.mapper.*;
import com.zhixue.content.model.dto.*;
import com.zhixue.content.model.po.*;
import com.zhixue.content.service.*;
import com.zhixue.exception.ZhixuePlusException;
import com.zhixue.model.*;
import com.zhixue.r.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Auther: 李 力
 * @Date: 2025/4/6
 * @Description: com.zhixue.content.service.impl
 * @version: 1.0
 */
@Service
public class CourseBaseServiceImpl extends ServiceImpl<CourseBaseMapper, CourseBase> implements CourseBaseService {

    @Autowired
    private CourseBaseMapper courseBaseMapper;

    @Autowired
    private CourseMarketMapper marketMapper;

    @Autowired
    private CourseCategoryMapper categoryMapper;

    @Autowired
    private TeachplanMapper teachplanMapper;

    @Autowired
    private TeachplanService teachplanService;

    @Autowired
    private CourseTeacherMapper teacherMapper;

    @Override
    public PageResult<CourseBase> selectPageList(String JGId, PageParams pageParams, QueryCourseParamsDto paramsDto) {

        LambdaQueryWrapper<CourseBase> wrapper = new LambdaQueryWrapper<>();
        //名称
        wrapper.like(StringUtils.isNotEmpty(paramsDto.getCourseName()), CourseBase::getName, paramsDto.getCourseName());
        //审核状态
        wrapper.eq(StringUtils.isNotEmpty(paramsDto.getAuditStatus()), CourseBase::getAuditStatus, paramsDto.getAuditStatus());
        //发布状态
        wrapper.eq(StringUtils.isNotEmpty(paramsDto.getPublishStatus()), CourseBase::getStatus, paramsDto.getPublishStatus());
        //机构ID
        wrapper.eq(CourseBase::getCompanyId, Long.parseLong(JGId));
        Page<CourseBase> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        Page<CourseBase> result = courseBaseMapper.selectPage(page, wrapper);
        return new PageResult<>(result.getRecords(), result.getTotal(), pageParams.getPageNo(), pageParams.getPageSize());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CourseBaseInfoDto addCourse(AddCourseDto addCourseDto, Long companyId) {
        checkParams(companyId, addCourseDto);
        CourseBase courseBase = new CourseBase();
        BeanUtils.copyProperties(addCourseDto, courseBase);
        courseBase.setCompanyId(companyId);
        // todo 创建人 更新人待完成
        //课程基本信息表写入
        boolean result = save(courseBase);
        if (result) {
            //课程营销表写入
            CourseMarket courseMarket = new CourseMarket();
            BeanUtils.copyProperties(addCourseDto, courseMarket);
            courseMarket.setId(courseBase.getId());
            result = saveOrUpdate(courseMarket);
            if (result) {
                //查询完整的信息
                return getCourseBaseInfoDto(courseBase.getId());
            }
        }
        return null;
    }

    private void checkParams(Long companyId, AddCourseDto addCourseDto) {
        if (addCourseDto == null || companyId == null) {
            throw new ZhixuePlusException("参数为空");
        }
        if (StringUtils.isEmpty(addCourseDto.getName())) {
            throw new ZhixuePlusException("课程名称不能为空");
        }
        if (StringUtils.isEmpty(addCourseDto.getUsers())) {
            throw new ZhixuePlusException("适用人群不能为空");
        }
        if (StringUtils.isEmpty(addCourseDto.getMt())) {
            throw new ZhixuePlusException("课程分类不能为空");
        }
        if (StringUtils.isEmpty(addCourseDto.getSt())) {
            throw new ZhixuePlusException("课程分类不能为空");
        }
        if (StringUtils.isEmpty(addCourseDto.getGrade())) {
            throw new ZhixuePlusException("课程等级不能为空");
        }
        if (StringUtils.isEmpty(addCourseDto.getCharge())) {
            throw new ZhixuePlusException("收费规则不能为空");
        }
        if ("201001".equals(addCourseDto.getCharge()) && addCourseDto.getPrice() == null) {
            throw new ZhixuePlusException("收费价格不能为空");
        }
        if (addCourseDto.getPrice() <= 0) {
            throw new ZhixuePlusException("收费价格不小于0");
        }
    }

    private boolean saveOrUpdate(CourseMarket courseMarket) {
        return marketMapper.insertOrUpdate(courseMarket);
    }

    private CourseBaseInfoDto getCourseBaseInfoDto(Long courseId) {
        CourseBase courseBase = getById(courseId);
        if (courseBase == null) {
            return null;
        }
        CourseMarket courseMarket = marketMapper.selectById(courseId);
        if (courseMarket == null) {
            return null;
        }
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase, courseBaseInfoDto);
        BeanUtils.copyProperties(courseMarket, courseBaseInfoDto);
        CourseCategory courseCategory1 = categoryMapper.selectById(courseBaseInfoDto.getMt());
        courseBaseInfoDto.setMtName(courseCategory1.getName());
        CourseCategory courseCategory2 = categoryMapper.selectById(courseBaseInfoDto.getSt());
        courseBaseInfoDto.setStName(courseCategory2.getName());
        return courseBaseInfoDto;
    }


    @Override
    public CourseBaseInfoDto getInfoById(Long courseId) {
        if (courseId == null) {
            throw new ZhixuePlusException("参数为null");
        }
        //查询基本信息
        return getCourseBaseInfoDto(courseId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public CourseBaseInfoDto updateCourse(Long companyId, EditCourseDto editCourseDto) {
        checkParams(companyId, editCourseDto);
        //todo 机构ID，更新人待后续完善
        //查询课程信息
        CourseBase courseBase = courseBaseMapper.selectById(editCourseDto.getId());
        if (courseBase == null) {
            throw new ZhixuePlusException("课程不存在");
        }
        if (!companyId.equals(courseBase.getCompanyId())) {
            throw new ZhixuePlusException("本机构只能修改本机构的课程");
        }
        BeanUtils.copyProperties(editCourseDto, courseBase);
        int result = courseBaseMapper.updateById(courseBase);
        if (result <= 0) {
            throw new ZhixuePlusException("更新失败");
        }
        return getCourseBaseInfoDto(courseBase.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R deleteById(Long id) {
        // todo 机构只能删除个人的课程 课程图片
        if (id == null) {
            throw new ZhixuePlusException("参数为null");
        }
        CourseBase courseBase = getById(id);
        if (!"202002".equals(courseBase.getAuditStatus())) {
            throw new ZhixuePlusException("不能删除");
        }
        int result = courseBaseMapper.deleteById(id);
        if (result > 0) {
            //删除课程营销信息
            result = marketMapper.deleteById(id);
            if (result > 0) {
                //删除课程计划以及关联的信息
                List<Long> ids = teachplanMapper.selectIds(id);
                ids.forEach(item -> {
                    R r = teachplanService.deleteById(item);
                    if (r.getCode() != 200) {
                        throw new ZhixuePlusException("删除失败");
                    }
                });
                //删除师资信息
                List<Long> tIds = teacherMapper.selectIds(id);
                result = teacherMapper.deleteByIds(tIds);
                return result > 0 ? R.ok() : R.fail();
            }
        }
        return null;
    }
}
